/**
 * 自动轮询监测页面资源（打包后的index.html）是否有发生变化（重新发布过），若有则刷新页面
 */
import env from "/@/base/env";

const enable = env.mode === "production" || env.mode === "staging";
// const enable = true;

let curHtml = "";
async function getHtml() {
  //读取index html
  const html = await fetch("/").then((res) => res.text());
  return html;
}

let curInter: number | null = null;
function start() {
  if (curInter !== null) {
    clearTimeout(curInter);
  }
  curInter = window.setTimeout(async () => {
    const newHtml = await getHtml();
    const oldArr = parseScript(curHtml);
    const newArr = parseScript(newHtml);
    const isSame = compare(oldArr, newArr);
    if (isSame) {
      curInter = null;
      start();
    } else {
      //
      location.reload();
    }
  }, 5000);
}
function parseScript(html) {
  const reg = new RegExp(/<script(?:\s+[^>]*)?>(.*?)<\/script\s*>/gi);
  return html.match(reg) as string[];
}
function compare(oldArr: string[], newArr: string[]) {
  const base = oldArr.length;
  const arr = Array.from(new Set(oldArr.concat(newArr)));
  //如果新旧length 一样无更新
  //否则有更新
  return arr.length === base;
}
export default {
  async init() {
    // console.log("=======>updater init", enable);
    if (enable) {
      curHtml = await getHtml();
      start();
    }
  },
};
